﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Xfm.Core.Table
{
    public class PageRequest
    {
        private int _start = 0;
        private int _length = 10;
        /// <summary>
        /// 页码,默认0
        /// </summary>
        public int Start
        {
            get
            {
                if (_start < 0)
                    return 0;
                else return _start;
            }
            set
            {
                _start = value;
            }
        }
        /// <summary>
        /// 每页多少条数据
        /// </summary>
        public int Length
        {
            get
            {
                if (_length < 1)
                    return 1;
                //限制最大1000；
                if (_length > 1000)
                    return 1000;
                return _length;
            }
            set
            {
                _length = value;
            }
        }
        /// <summary>
        /// 排序字段
        /// </summary>
        public string OrderBy { get; set; }
        /// <summary>
        /// 是否顺序
        /// </summary>
        public bool IsAsc { get; set; }
        /// <summary>
        /// 最大
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public PageData<T> GetData<T>(IQueryable<T> source)
        {
            PageData<T> page = new PageData<T>();
            page.Length = Length;
            page.Index = Start;
            page.Total = source.Count();
            int maxPage = (int)Math.Ceiling(page.Total / (double)page.Length);
            if (page.Index > maxPage)
            {
                //前端页码超出限制
                page.Index = maxPage - 1;
            }
            if (!string.IsNullOrWhiteSpace(OrderBy))
            {
                source = source.OrderString(OrderBy, IsAsc);
                //source.OrderBy(m=>EF.Property(source, OrderBy));
            }
            page.Data = source.Skip(page.Index * page.Length).Take(page.Length);
            return page;
        }
        public PageData<object> Getdata(IQueryable<object> source)
        {
            return GetData<object>(source);
        }
    }
}
